"""
https://docs.streamlit.io/get-started/tutorials/create-an-app
"""

import streamlit as st
import pandas as pd
import numpy as np
import time
from streamlit_cookies_controller import CookieController
from PyCmpltrtok.common import uuid


# 写入cookie
def set_cookie(name, value, days=30):
    expires = days * 24 * 60 * 60
    st.markdown(f"""
        <script>
        document.cookie = "{name}={value}; max-age={expires}";
        </script>
        """, unsafe_allow_html=True)
    

def get_all_cookies():
    '''
    WARNING: This uses unsupported feature of Streamlit
    Returns the cookies as a dictionary of kv pairs
    '''
    from streamlit.web.server.websocket_headers import _get_websocket_headers 
    # https://github.com/streamlit/streamlit/pull/5457
    from urllib.parse import unquote

    headers = _get_websocket_headers()
    if headers is None:
        return {}
    
    if 'Cookie' not in headers:
        return {}
    
    cookie_string = headers['Cookie']
    # A sample cookie string: "K1=V1; K2=V2; K3=V3"
    cookie_kv_pairs = cookie_string.split(';')

    cookie_dict = {}
    for kv in cookie_kv_pairs:
        k_and_v = kv.split('=')
        k = k_and_v[0].strip()
        v = k_and_v[1].strip()
        cookie_dict[k] = unquote(v) #e.g. Convert name%40company.com to name@company.com
    return cookie_dict


st.title('Uber pickups in NYC')

cookies = get_all_cookies()
for k, v in cookies.items():
    st.text(f'{k} = {v}')
st.markdown('''
---
''')
USERNAME = 'uname_of_st'
username = cookies.get(USERNAME, '<None>')
if '<None>' == username:
    xuuid = uuid()
    
    # set_cookie(USERNAME, xuuid)
    controller = CookieController()
    controller.set(USERNAME, xuuid, max_age=3600*24*30)
    
    username = xuuid
    st.text(f'new username = {username}')
st.text(f'username = {username}')

DATE_COLUMN = 'date/time'
DATA_URL = '/home/yunpeng/download/uber-raw-data-sep14.csv.gz'


@st.cache_data
def load_data(nrows):
    data = pd.read_csv(DATA_URL, nrows=nrows)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
    time.sleep(3)
    return data


##################################################################################
data_load_state = st.text('Loading data ...')

data = load_data(10000)

data_load_state.text('Loading data done!')

##################################################################################
st.subheader('Raw data')
if st.checkbox('Show raw data'):

    data

    st.write(data)

    st.dataframe(data)

##################################################################################
st.subheader('Number of pickups by hour')

hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0, 24))[0]

hist_values

st.bar_chart(hist_values)

##################################################################################
st.subheader('Map of all pickups')

map_load_state = st.text('Loading map ...')
st.map(data)
map_load_state.text('Done')

##################################################################################
st.subheader('Map of all pickups FILTERED')

map_load_state = st.text('Loading map ...')
hour_to_filter = 17
filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter]
st.map(filtered_data)
map_load_state.text('Done')

##################################################################################
st.subheader('Map of all pickups FILTERED SLIDER')

map_load_state = st.text('Loading map ...')
hour_to_filter = st.slider('hour', 0, 23, 17) 
filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter]
st.map(filtered_data)
map_load_state.text('Done')

##################################################################################
st.subheader('Try my slider')
my_slider = st.slider('My slider', 0, 10, 5)
st.text(my_slider)
